#include <iostream>
#include <string>
#include <vector>
#include <boost/filesystem.hpp>
#include "utils.hpp"
#include "Log.hpp"

const std::string src_path = "/home/br/Code/Boost_Engine/data/input";
const std::string output = "/home/br/Code/Boost_Engine/data/raw_html/raw.txt";

typedef struct DocInfo
{
    std::string title;   // 文档标题
    std::string content; // 文档内容
    std::string url;     // 文档对应链接
} DocInfo_t;

// const &: 输入
//*: 输出
//&：输入输出

bool EnumFile(const std::string &filesrc, std::vector<std::string> *file_list);
bool ParseHtml(const std::vector<std::string> &file_list, std::vector<DocInfo_t> *results);
bool SaveHtml(const std::vector<DocInfo_t> &results, const std::string &output);
int main()
{
    std::vector<std::string> file_list;
    // 第一步: 递归式的把每个html文件名带路径，保存到files_list中，
    // 方便后期进行一个一个的文件进行读取
    if (!EnumFile(src_path, &file_list))
    {
        std::cerr << "Enum File error" << std::endl;
        return 1;
    }
    // 第二步: 按照files_list读取每个文件的内容，并进行解析
    std::vector<DocInfo_t> results;
    if (!ParseHtml(file_list, &results))
    {
        std::cerr << "Parse file error" << std::endl;
        return 2;
    }
    // 第三步: 把解析完毕的各个文件内容，写入到output,按照\3作为每个文档的分割符
    if (!SaveHtml(results, output))
    {
        std::cerr << "Save Html error";
        return 3;
    }
    return 0;
}

bool EnumFile(const std::string &filesrc, std::vector<std::string> *file_list)
{
    namespace fs = boost::filesystem;
    // 创建path对象root_path
    fs::path root_path(filesrc);
    // 判断src_path是否存在
    if (!fs::exists(root_path))
    {
        std::cerr << filesrc << "not exists" << std::endl;
        return false;
    }
    // 定义一个空迭代器，用来判定递归结束
    fs::recursive_directory_iterator end;
    int count = 0;
    for (fs::recursive_directory_iterator iter(root_path); iter != end; iter++)
    {
        if (!fs::is_regular_file(*iter)) // 判断是否为普通文件，不是则跳过
            continue;
        if (iter->path().extension() != ".html") // 判断后缀是否为.html，不是则跳过
            continue;
        file_list->push_back(iter->path().string()); // 插入文件路径
    }
    LOG(NORMAL,"EnumFIle finish");
    return true;
}
static bool ParseTitle(const std::string &result, std::string *doc)
{
    int begin = result.find("<title>");
    if (begin == std::string::npos)
        return false;

    int end = result.find("</title>");
    if (end == std::string::npos)
        return false;

    begin += std::string("<title>").size();

    if (begin > end)
        return false;

    
    *doc = result.substr(begin, end - begin);
    return true;
}
static bool ParseContent(const std::string &result, std::string *doc)
{
    enum Level
    {
        UNABLE,
        CONTENT
    };
    enum Level s = UNABLE;
    for (char e : result)
    {
        switch (s)
        {
        case UNABLE:
            if (e == '>')
            {
                s = CONTENT;
            }
            break;
        case CONTENT:
            if (e == '<')
            {
                s = UNABLE;
            }
            else
            {
                if (e == '\n')
                    *doc += ' ';
                else
                    *doc += e;
            }
            break;
        }
    }
    return true;
}
static bool ParseUrl(const std::string &file_path, std::string *doc)
{
    std::string url_head = "http://www.boost.org/doc/libs/1_88_0/doc/html";
    std::string url_neck = file_path.substr(src_path.size());

    *doc = url_head + url_neck;
    return true;
}

bool ParseHtml(const std::vector<std::string> &file_list, std::vector<DocInfo_t> *results)
{
    int count = 0;
    for (const std::string &file : file_list)
    {
        // 读取文档内容到result
        std::string result;
        if (!ns_util::FileUtil::ReadFile(file, &result))
        {
            std::cout << "can't rend file:" << file << std::endl;
            continue;
        }

        DocInfo_t doc;
        // 提取title
        if (!ParseTitle(result, &doc.title))
        {
            std::cout << "can't Parse title:" << std::endl;
            continue;
        }
        // 提取content
        if (!ParseContent(result, &doc.content))
        {
            std::cout << "can't Parse content:" << std::endl;
            continue;
        }
        // 提取并构建url
        if (!ParseUrl(file, &doc.url))
        {
            std::cout << "can't Parse url:" << std::endl;
            continue;
        }
        // 插入到results中
        results->push_back(std::move(doc));
        count++;
        std::cout << "ParseHtml:" <<  count << std::endl;;
    }
    return true;
}
bool SaveHtml(const std::vector<DocInfo_t> &results, const std::string &output)
{
    std::ofstream out(output, std::ios::out | std::ios::binary);
    if (!out.is_open())
    {
        std::cerr << "open " << output << std::endl;
        return false;
    }
    int count = 0;
    for (const DocInfo_t &doc : results)
    {
        std::string out_string;
        out_string += doc.title;
        out_string += '\3';
        out_string += doc.content;
        out_string += '\3';
        out_string += doc.url;
        out_string += '\n';
        out.write(out_string.c_str(), out_string.size());
        count++;
    }
    std::cout << "SaveHtml:" << count << std::endl;
    out.close();
    return true;
}
